#include <QVariant>
#include <QThreadPool>
#include "XCompareDir.h"
#include "XCompareRunnable.h"
#include "XCompareMangerThread.h"

XCompareMangerThread::XCompareMangerThread(QObject* parent /*= nullptr*/)
	:QThread(parent)
{

}

XCompareMangerThread::~XCompareMangerThread()
{
	if (m_pCurrentTask)
	{
		m_pCurrentTask->Valid(false);
	}
}

void XCompareMangerThread::setCurrentCompareDir(const QString& left, const QString& right)
{
	if (m_pCurrentTask)
	{
		m_pCurrentTask->Valid(false);
	}
	m_pCurrentTask = (XTaskPtr)new XTask(left, right, this);
}

void XCompareMangerThread::fastCompareDir(const QString& left, const QString& right)
{
	NULL_RETURN(m_pCurrentTask);
	m_pCurrentTask->fastCompareDir(left, right);
}

void XCompareMangerThread::onCompairResult(QVariantList listData, XTaskPtr task)
{
	if (false == task->Valid() || task != m_pCurrentTask)
	{
		return;
	}

	if (listData.length() != 3)
	{
		return;
	}
	auto var = listData[0].toList();
	for (auto iter = var.begin(); iter != var.end(); iter++)
	{
		auto value = iter->toList();

		auto typeCompare = value[1].value<XCompareType>();
		if (typeCompare == 1)
		{
			QString left,right;
			if (value[0].isValid())
			{
				left = value[0].value<QFileInfo>().absoluteFilePath();
			}
			if (value[2].isValid())
			{
				right = value[2].value<QFileInfo>().absoluteFilePath();
			}
			task->setParam(left, right);
		}

		//TODO: create item tree


		//auto tmp1 = value[0].value<QFileInfo>();
		//auto tmp2 = value[1].value<CompareType>();
		//if (File_Equal == tmp2 && tmp1.isDir())
		//{
		//	auto tmp3 = value[2].value<QFileInfo>();
		//	m_task->setParam(tmp1.absoluteFilePath(), tmp3.absoluteFilePath());
			
			// QThreadPool takes ownership and deletes 'hello' automatically
		//	QThreadPool::globalInstance()->start(hello);
		//}
	}
}

void XCompareMangerThread::run()
{
	while (m_bRun)
	{
		QThread::msleep(100);
		auto pairTmp = m_pCurrentTask->getParam();
		XCompareRunnable* runTmp = new XCompareRunnable(pairTmp.first, pairTmp.second, m_pCurrentTask);
		connect(runTmp, &XCompareRunnable::sigCompairResult, this, &XCompareMangerThread::onCompairResult);
		QThreadPool::globalInstance()->start(runTmp);
	}
}
